﻿using Audiobus.API;
using GZHJ.Tool;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using VM.Shared.TestAttribute;

namespace 奥普新音频分析仪
{
    public class 音频分析仪
    {
        [ExposedMethodAttribute("")]
        public bool 波形输出(out string 错误信息, bool 打开 = true, double 频率 = 1000, double 幅值 = 0.5)
        {
            错误信息 = "";
            try
            {
                AD2000 aD2000 = new AD2000(ADOperatingMode.SequenceMode, false);
                aD2000.Visible = true;
                aD2000.SignalPathSetup.Generator.On = 打开;
                aD2000.SignalPathSetup.Generator.Levels.SetValue(OutputChannelIndex.Ch1, 幅值);
                aD2000.SignalPathSetup.Generator.Frequency.Value = 频率;

                return true;
            }
            catch (Exception ex)
            {
                //错误信息 = ex.Message;
                //throw;

                //更改提示消息为自定义中文提示的方式，2024-11-25
                LogHelper.Error($"[音频分析仪.波形输出]异常，{ex.Message}，{ex.StackTrace}");
                错误信息 = CommonWay.GetAppConfigKeyValue("A_1001");
                if (string.IsNullOrWhiteSpace(错误信息))
                {
                    错误信息 = ex.Message;  //如果无配置文件，则还是英文具体提示的方式
                }
            }

            return false;
        }
        [ExposedMethodAttribute("")]
        public bool 输入通道切换(int StationNumb, out string 错误信息)
        {
            错误信息 = "";
            SwitcherChannelSelection switcherA1 = SwitcherChannelSelection.Ch1;
            SwitcherChannelSelection switcherA2 = SwitcherChannelSelection.Ch2;
            SwitcherChannelSelection switcherB1 = SwitcherChannelSelection.Ch1;
            SwitcherChannelSelection switcherB2 = SwitcherChannelSelection.Ch2;
            switch (StationNumb)
            {
                case 1:
                    switcherA1 = SwitcherChannelSelection.Ch1;
                    switcherA2 = SwitcherChannelSelection.Ch2;
                    switcherB1 = SwitcherChannelSelection.Ch1;
                    switcherB2 = SwitcherChannelSelection.Ch2;
                    break;
                case 2:
                    switcherA1 = SwitcherChannelSelection.Ch3;
                    switcherA2 = SwitcherChannelSelection.Ch4;
                    switcherB1 = SwitcherChannelSelection.Ch3;
                    switcherB2 = SwitcherChannelSelection.Ch4;
                    break;
                default:
                    switcherA1 = SwitcherChannelSelection.Ch1;
                    switcherA2 = SwitcherChannelSelection.Ch2;
                    switcherB1 = SwitcherChannelSelection.Ch1;
                    switcherB2 = SwitcherChannelSelection.Ch2;
                    break;
            }
            try
            {
                AD2000 aD2000 = new AD2000(ADOperatingMode.SequenceMode, true);
                aD2000.Visible = true;
                var inputSwitcher = aD2000.SignalPathSetup.InputSwitcherConfiguration;
                inputSwitcher.SetChannelA(SwitcherAddress.Switcher0, switcherA1);
                inputSwitcher.SetChannelB(SwitcherAddress.Switcher0, switcherA2);

                inputSwitcher.SetChannelA(SwitcherAddress.Switcher1, switcherB1);
                inputSwitcher.SetChannelB(SwitcherAddress.Switcher1, switcherB2);
                aD2000.SignalPathSetup.UseInputSwitcher = true;

                return true;
            }
            catch (Exception ex)
            {
                //错误信息 = ex.Message;
                //throw;

                //更改提示消息为自定义中文提示的方式，2024-11-25
                LogHelper.Error($"[音频分析仪.输入通道切换]异常，{ex.Message}，{ex.StackTrace}");
                错误信息 = CommonWay.GetAppConfigKeyValue("A_1002");
                if (string.IsNullOrWhiteSpace(错误信息))
                {
                    错误信息 = ex.Message;  //如果无配置文件，则还是英文具体提示的方式
                }
            }

            return false;
        }
        [ExposedMethodAttribute("")]
        public bool 切换指定输入通道(int StationNumb, int 通道, out string 错误信息)
        {
            错误信息 = "";
            SwitcherChannelSelection switcher = SwitcherChannelSelection.Ch1;
            switch (通道)
            {
                case 1:
                    switcher = SwitcherChannelSelection.Ch1;
                    break;
                case 2:
                    switcher = SwitcherChannelSelection.Ch2;
                    break;
                case 3:
                    switcher = SwitcherChannelSelection.Ch3;
                    break;
                case 4:
                    switcher = SwitcherChannelSelection.Ch4;
                    break;
                case 5:
                    switcher = SwitcherChannelSelection.Ch5;
                    break;
                case 6:
                    switcher = SwitcherChannelSelection.Ch6;
                    break;
                case 7:
                    switcher = SwitcherChannelSelection.Ch7;
                    break;
                case 8:
                    switcher = SwitcherChannelSelection.Ch8;
                    break;
                case 9:
                    switcher = SwitcherChannelSelection.Ch9;
                    break;
                case 10:
                    switcher = SwitcherChannelSelection.Ch10;
                    break;
                case 11:
                    switcher = SwitcherChannelSelection.Ch11;
                    break;
                case 12:
                    switcher = SwitcherChannelSelection.Ch12;
                    break;
                default:
                    break;
            }
            try
            {
                AD2000 aD2000 = new AD2000(ADOperatingMode.SequenceMode, true);
                aD2000.Visible = true;
                var inputSwitcher = aD2000.SignalPathSetup.InputSwitcherConfiguration;
                switch (StationNumb)
                {
                    case 1: inputSwitcher.SetChannelA(SwitcherAddress.Switcher0, switcher); break;
                    case 2: inputSwitcher.SetChannelA(SwitcherAddress.Switcher1, switcher); break;
                    default: inputSwitcher.SetChannelA(SwitcherAddress.Switcher0, switcher); break;
                }
                aD2000.SignalPathSetup.UseInputSwitcher = true;

                return true;
            }
            catch (Exception ex)
            {
                //错误信息 = ex.Message;
                //throw;

                //更改提示消息为自定义中文提示的方式，2024-11-25
                LogHelper.Error($"[音频分析仪.切换指定输入通道]异常，{ex.Message}，{ex.StackTrace}");
                错误信息 = CommonWay.GetAppConfigKeyValue("A_1003");
                if (string.IsNullOrWhiteSpace(错误信息))
                {
                    错误信息 = ex.Message;  //如果无配置文件，则还是英文具体提示的方式
                }
            }

            return false;
        }
        [ExposedMethodAttribute("")]
        public bool 通道切换(int Numb1, int Numb2, out string 错误信息)
        {
            错误信息 = "";
            SwitcherChannelSelection switcherA1 = (SwitcherChannelSelection)Numb1;
            SwitcherChannelSelection switcherA2 = (SwitcherChannelSelection)Numb2;


            try
            {
                AD2000 aD2000 = new AD2000(ADOperatingMode.SequenceMode, true);
                aD2000.Visible = true;
                var inputSwitcher = aD2000.SignalPathSetup.InputSwitcherConfiguration;
                inputSwitcher.SetChannelA(SwitcherAddress.Switcher0, switcherA1);
                inputSwitcher.SetChannelB(SwitcherAddress.Switcher0, switcherA2);


                aD2000.SignalPathSetup.UseInputSwitcher = true;

                return true;
            }
            catch (Exception ex)
            {
                //错误信息 = ex.Message;
                //throw;

                //更改提示消息为自定义中文提示的方式，2024-11-25
                LogHelper.Error($"[音频分析仪.通道切换]异常，{ex.Message}，{ex.StackTrace}");
                错误信息 = CommonWay.GetAppConfigKeyValue("A_1004");
                if (string.IsNullOrWhiteSpace(错误信息))
                {
                    错误信息 = ex.Message;  //如果无配置文件，则还是英文具体提示的方式
                }
            }
            return false;
        }

        [ExposedMethodAttribute("")]
        public bool 蓝牙通话通道(out string 错误信息)
        {
            错误信息 = "";
            SwitcherChannelSelection switcherA1 = SwitcherChannelSelection.Ch7;
            SwitcherChannelSelection switcherA2 = SwitcherChannelSelection.Ch8;


            try
            {
                AD2000 aD2000 = new AD2000(ADOperatingMode.SequenceMode, true);
                aD2000.Visible = true;
                var inputSwitcher = aD2000.SignalPathSetup.InputSwitcherConfiguration;
                inputSwitcher.SetChannelA(SwitcherAddress.Switcher1, switcherA1);
                inputSwitcher.SetChannelB(SwitcherAddress.Switcher1, switcherA2);


                aD2000.SignalPathSetup.UseInputSwitcher = true;

                return true;
            }
            catch (Exception ex)
            {
                //错误信息 = ex.Message;
                //throw;

                //更改提示消息为自定义中文提示的方式，2024-11-25
                LogHelper.Error($"[音频分析仪.蓝牙通话通道]异常，{ex.Message}，{ex.StackTrace}");
                错误信息 = CommonWay.GetAppConfigKeyValue("A_1005");
                if (string.IsNullOrWhiteSpace(错误信息))
                {
                    错误信息 = ex.Message;  //如果无配置文件，则还是英文具体提示的方式
                }
            }

            return false;
        }

        [ExposedMethodAttribute("")]
        public bool 读取测试值(out string 错误信息, out double[] 频率, out double[] 幅值, out double[] 失真)
        {
            错误信息 = "";
            频率 = new List<double> { 0 }.ToArray();
            幅值 = new List<double> { 0.0, 0.0, 0.0, 0.0 }.ToArray();
            失真 = new List<double> { 0.0, 0.0, 0.0, 0.0 }.ToArray();
            List<double> doubles;
            try
            {
                AD2000 aD2000 = new AD2000(ADOperatingMode.SequenceMode, true);
                aD2000.Visible = true;

                doubles = new List<double>();
                foreach (string item in aD2000.SignalMeters.FrequencyMeter.Text)
                {
                    doubles.Add(截取频率值(item));
                }
                频率 = doubles.ToArray();

                doubles = new List<double>();
                foreach (string item in aD2000.SignalMeters.ThdNMeter.Text)
                {
                    doubles.Add(截取失真值(item));
                }
                失真 = doubles.ToArray();

                doubles = new List<double>();
                foreach (string item in aD2000.SignalMeters.LevelMeter.Text)
                {
                    doubles.Add(截取幅值值(item));
                }
                幅值 = doubles.ToArray();
                //将读取到的数据追加到错误信息中，方便测试报告中查看，2024-10-29
                错误信息 = $"频率：{string.Join(",", 频率)}。幅值：{string.Join(",", 幅值)}。失真：{string.Join(",", 失真)}。";

                return true;
            }
            catch (Exception ex)
            {
                错误信息 = ex.Message;
                //将读取到的数据追加到错误信息中，方便测试报告中查看，2024-10-29
                错误信息 += $"频率：{string.Join(",", 频率)}。幅值：{string.Join(",", 幅值)}。失真：{string.Join(",", 失真)}。";
                LogHelper.Error($"[音频分析仪.读取测试值]异常，{ex.Message}，{ex.StackTrace}");
            }

            return false;
        }
        [ExposedMethodAttribute("")]
        public bool 读取测试值平均值(out string 错误信息, out double[] 频率, out double[] 幅值, out double[] 失真, int 总次数 = 10)
        {
            错误信息 = "";
            频率 = new List<double> { 0 }.ToArray();
            幅值 = new List<double> { 0.0, 0.0, 0.0, 0.0 }.ToArray();
            失真 = new List<double> { 0.0, 0.0, 0.0, 0.0 }.ToArray();
            List<double> doubles;
            try
            {
                if (总次数 <= 0)
                {
                    总次数 = 1;  //最小需要统计1次
                }
                AD2000 aD2000 = new AD2000(ADOperatingMode.SequenceMode, true);
                aD2000.Visible = true;
                List<List<double>> 频率列表 = new List<List<double>>();
                List<List<double>> 幅值列表 = new List<List<double>>();
                List<List<double>> 失真列表 = new List<List<double>>();

                for (int i = 0; i < 总次数; i++)
                {
                    doubles = new List<double>();
                    foreach (string item in aD2000.SignalMeters.FrequencyMeter.Text)
                    {
                        doubles.Add(截取频率值(item));
                    }
                    频率列表.Add(doubles);

                    doubles = new List<double>();
                    foreach (string item in aD2000.SignalMeters.ThdNMeter.Text)
                    {
                        doubles.Add(截取失真值(item));
                    }
                    失真列表.Add(doubles);

                    doubles = new List<double>();
                    foreach (string item in aD2000.SignalMeters.LevelMeter.Text)
                    {
                        doubles.Add(截取幅值值(item));
                    }
                    幅值列表.Add(doubles);
                }
                频率 = GetAverageValueByList(频率列表).ToArray();
                失真 = GetAverageValueByList(失真列表).ToArray();
                幅值 = GetAverageValueByList(幅值列表).ToArray();

                //将读取到的数据追加到错误信息中，方便测试报告中查看，2024-10-29
                错误信息 = $"频率：{string.Join(",", 频率)}。幅值：{string.Join(",", 幅值)}。失真：{string.Join(",", 失真)}。";

                return true;
            }
            catch (Exception ex)
            {
                错误信息 = ex.Message;
                //将读取到的数据追加到错误信息中，方便测试报告中查看，2024-10-29
                错误信息 += $"频率：{string.Join(",", 频率)}。幅值：{string.Join(",", 幅值)}。失真：{string.Join(",", 失真)}。";
                LogHelper.Error($"[音频分析仪.读取测试值平均值]异常，{ex.Message},{ex.StackTrace}");
            }

            return false;
        }

        private double 截取值(string input, string pattern)
        {
            try
            {
                Match match = Regex.Match(input, pattern);
                if (match.Success)
                {
                    // 提取第一个括号内的数字
                    Group numberGroup = match.Groups[1];
                    return Convert.ToDouble(numberGroup.Value);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error($"[音频分析仪.截取值]异常，{ex.Message}，{ex.StackTrace}");
            }

            return 0.0;
        }
        private double 截取失真值(string input)
        {
            try
            {
                string pattern = @"(\d+)\s*kHz";//mVrms
                if (input.Contains("%"))
                {
                    pattern = input.Replace("%", "").Trim();
                    return Convert.ToDouble(pattern);
                }

                Match match = Regex.Match(input, pattern);
                if (match.Success)
                {
                    // 提取第一个括号内的数字
                    Group numberGroup = match.Groups[1];
                    return Convert.ToDouble(numberGroup.Value);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error($"[音频分析仪.截取失真值]异常，{ex.Message}，{ex.StackTrace}");
            }

            return 0.0;
        }
        private double 截取频率值(string input)
        {
            try
            {
                string pattern = @"(\d+)\s*kHz";//mVrms
                if (input.Contains("kHz"))
                {
                    pattern = input.Replace("kHz", "").Trim();
                    return Convert.ToDouble(pattern);
                }

                Match match = Regex.Match(input, pattern);
                if (match.Success)
                {
                    // 提取第一个括号内的数字
                    Group numberGroup = match.Groups[1];
                    return Convert.ToDouble(numberGroup.Value);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error($"[音频分析仪.截取频率值]异常，{ex.Message}，{ex.StackTrace}");
            }

            return 0.0;
        }

        private double 截取幅值值(string input)
        {
            try
            {
                string pattern = @"(\d+)\s*Vrms";//mVrms
                if (input.Contains("uVrms"))
                {
                    pattern = input.Replace("uVrms", "").Trim();
                    return Convert.ToDouble(pattern) / 1000 / 1000;
                }
                else if (input.Contains("mVrms"))
                {
                    pattern = @"(\d+)\s*mVrms";
                    pattern = input.Replace("mVrms", "").Trim();
                    return Convert.ToDouble(pattern) / 1000;
                }
                else if (input.Contains("Vrms"))
                {
                    pattern = input.Replace("Vrms", "").Trim();
                    return Convert.ToDouble(pattern);
                }
                Match match = Regex.Match(input, pattern);
                if (match.Success)
                {
                    // 提取第一个括号内的数字
                    Group numberGroup = match.Groups[1];
                    return Convert.ToDouble(numberGroup.Value);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error($"[音频分析仪.截取幅值值]异常，{ex.Message}，{ex.StackTrace}");
            }

            return 0.0;
        }
        /// <summary>
        /// 获取嵌套列表的列表平均值
        /// </summary>
        /// <returns></returns>
        private List<double> GetAverageValueByList(List<List<double>> list)
        {
            // 确保所有List长度相同
            int listLength = list[0].Count;
            if (!list.All(obj => obj.Count == listLength))
            {
                LogHelper.Error($"[音频分析仪.GetAverageValueByList]获取嵌套列表的列表平均值失败，列表长度不相同，默认使用第一个数据的值");
                return list[0];  //所有List的长度不同，默认使用List[0]的值
            }

            List<double> averageList = new List<double>();
            for (int i = 0; i < list[0].Count; i++)
            {
                double average = list.Average(obj => obj[i]);
                averageList.Add(average);
            }
            return averageList;
        }
    }
}
